package cn.lblbc.todo

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs

class MainActivity : AppCompatActivity() {
    private lateinit var taskGroupAdapter: TaskGroupAdapter
    private var showCompletedTasks = false
    private var dateFilterOption = DateFilter.ALL
    private lateinit var menu: Menu
    
    companion object {
        private const val REQUEST_CODE_REFRESH = 1001
        const val EXTRA_TASK = "extra_task"
    }
    
    // 日期筛选选项枚举
    enum class DateFilter {
        TODAY, TOMORROW, ALL
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 初始化TaskManager
        TaskManager.init(this)
        
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        // 设置工具栏
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        
        // 设置任务列表
        val recyclerView = findViewById<RecyclerView>(R.id.taskRecyclerView)
        taskGroupAdapter = TaskGroupAdapter(
            emptyList(),
            { task, isChecked -> 
                // 处理任务完成状态改变
                task.isCompleted = isChecked
                TaskManager.updateTask(task)
            },
            { task ->
                // 处理任务点击事件
                val intent = Intent(this, AddEditTaskActivity::class.java)
                intent.putExtra(EXTRA_TASK, task)
                startActivityForResult(intent, REQUEST_CODE_REFRESH)
            }
        )
        recyclerView.adapter = taskGroupAdapter
        recyclerView.layoutManager = LinearLayoutManager(this)
        
        // 添加间距装饰器
        val spacingInPixels = resources.getDimension(R.dimen.card_spacing).toInt()
        recyclerView.addItemDecoration(SpaceItemDecoration(spacingInPixels))
        
        // 观察任务数据变化
        observeTasks()
        
        // 设置添加任务按钮的点击事件
        val addTaskButton = findViewById<ImageView>(R.id.addTaskButton)
        addTaskButton.setOnClickListener {
            val intent = Intent(this, AddEditTaskActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_REFRESH)
        }
    }
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        this.menu = menu
        
        // 根据当前筛选选项设置菜单项选中状态
        when (dateFilterOption) {
            DateFilter.TODAY -> menu.findItem(R.id.menu_date_today).isChecked = true
            DateFilter.TOMORROW -> menu.findItem(R.id.menu_date_tomorrow).isChecked = true
            DateFilter.ALL -> menu.findItem(R.id.menu_date_all).isChecked = true
        }
        
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_show_completed -> {
                item.isChecked = !item.isChecked
                showCompletedTasks = item.isChecked
                observeTasks()
                true
            }
            R.id.menu_date_today -> {
                item.isChecked = true
                dateFilterOption = DateFilter.TODAY
                observeTasks()
                true
            }
            R.id.menu_date_tomorrow -> {
                item.isChecked = true
                dateFilterOption = DateFilter.TOMORROW
                observeTasks()
                true
            }
            R.id.menu_date_all -> {
                item.isChecked = true
                dateFilterOption = DateFilter.ALL
                observeTasks()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    private fun observeTasks() {
        lifecycleScope.launch {
            if (showCompletedTasks) {
                TaskManager.getAllTasks().collect { tasks ->
                    val filteredTasks = filterTasksByDate(tasks)
                    val groupedTasks = groupTasksByDate(filteredTasks)
                    taskGroupAdapter.updateTaskGroups(groupedTasks)
                }
            } else {
                TaskManager.getActiveTasks().collect { tasks ->
                    val filteredTasks = filterTasksByDate(tasks)
                    val groupedTasks = groupTasksByDate(filteredTasks)
                    taskGroupAdapter.updateTaskGroups(groupedTasks)
                }
            }
        }
    }
    
    private fun filterTasksByDate(tasks: List<Task>): List<Task> {
        val today = Calendar.getInstance()
        today.set(Calendar.HOUR_OF_DAY, 0)
        today.set(Calendar.MINUTE, 0)
        today.set(Calendar.SECOND, 0)
        today.set(Calendar.MILLISECOND, 0)
        
        val tomorrow = Calendar.getInstance().apply {
            time = today.time
            add(Calendar.DAY_OF_MONTH, 1)
        }
        
        return when (dateFilterOption) {
            DateFilter.TODAY -> {
                tasks.filter { task ->
                    // 显示今天和已过期的任务
                    task.dueDate?.let { dueDate ->
                        val taskDate = Calendar.getInstance()
                        taskDate.time = dueDate
                        taskDate.set(Calendar.HOUR_OF_DAY, 0)
                        taskDate.set(Calendar.MINUTE, 0)
                        taskDate.set(Calendar.SECOND, 0)
                        taskDate.set(Calendar.MILLISECOND, 0)
                        taskDate.timeInMillis <= today.timeInMillis
                    } ?: false // 未设置日期的任务不显示
                }
            }
            DateFilter.TOMORROW -> {
                tasks.filter { task ->
                    // 仅显示明天的任务
                    task.dueDate?.let { dueDate ->
                        val taskDate = Calendar.getInstance()
                        taskDate.time = dueDate
                        taskDate.set(Calendar.HOUR_OF_DAY, 0)
                        taskDate.set(Calendar.MINUTE, 0)
                        taskDate.set(Calendar.SECOND, 0)
                        taskDate.set(Calendar.MILLISECOND, 0)
                        taskDate.timeInMillis == tomorrow.timeInMillis
                    } ?: false // 未设置日期的任务不显示
                }
            }
            DateFilter.ALL -> {
                // 显示所有任务
                tasks
            }
        }
    }
    
    private fun groupTasksByDate(tasks: List<Task>): List<TaskGroup> {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val today = Calendar.getInstance()
        today.set(Calendar.HOUR_OF_DAY, 0)
        today.set(Calendar.MINUTE, 0)
        today.set(Calendar.SECOND, 0)
        today.set(Calendar.MILLISECOND, 0)
        
        // 分离未设置日期的任务
        val noDateTasks = tasks.filter { it.dueDate == null }
        
        // 分离今天及以后的任务
        val futureTasks = tasks.filter { task ->
            task.dueDate?.let { dueDate ->
                val taskDate = Calendar.getInstance()
                taskDate.time = dueDate
                taskDate.set(Calendar.HOUR_OF_DAY, 0)
                taskDate.set(Calendar.MINUTE, 0)
                taskDate.set(Calendar.SECOND, 0)
                taskDate.set(Calendar.MILLISECOND, 0)
                taskDate.timeInMillis >= today.timeInMillis
            } ?: false
        }
        
        // 分离今天之前的任务（已过期）
        val expiredTasks = tasks.filter { task ->
            task.dueDate?.let { dueDate ->
                val taskDate = Calendar.getInstance()
                taskDate.time = dueDate
                taskDate.set(Calendar.HOUR_OF_DAY, 0)
                taskDate.set(Calendar.MINUTE, 0)
                taskDate.set(Calendar.SECOND, 0)
                taskDate.set(Calendar.MILLISECOND, 0)
                taskDate.timeInMillis < today.timeInMillis
            } ?: false
        }
        
        // 按日期分组今天及以后的任务
        val futureGrouped = futureTasks.groupBy { task ->
            val taskDate = Calendar.getInstance()
            taskDate.time = task.dueDate!!
            taskDate.set(Calendar.HOUR_OF_DAY, 0)
            taskDate.set(Calendar.MINUTE, 0)
            taskDate.set(Calendar.SECOND, 0)
            taskDate.set(Calendar.MILLISECOND, 0)
            
            val diffInDays = ((taskDate.timeInMillis - today.timeInMillis) / (1000 * 60 * 60 * 24)).toInt()
            
            when (diffInDays) {
                0 -> "今天"
                1 -> "明天"
                2 -> "后天"
                else -> dateFormat.format(task.dueDate)
            }
        }
        
        // 创建排序后的列表
        val sortedGroups = mutableListOf<TaskGroup>()
        
        // 首先添加"未设置日期"的组（如果存在）
        if (noDateTasks.isNotEmpty()) {
            sortedGroups.add(TaskGroup("未设置日期", noDateTasks))
        }
        
        // 然后添加"已过期"的组（如果存在）
        if (expiredTasks.isNotEmpty()) {
            sortedGroups.add(TaskGroup("已过期", expiredTasks))
        }
        
        // 最后按实际日期排序添加今天及以后的组
        futureGrouped.map { (key, taskList) ->
            // 将"今天"、"明天"、"后天"转换为实际日期用于排序
            val sortKey = when (key) {
                "今天" -> dateFormat.format(today.time)
                "明天" -> {
                    val tomorrow = today.clone() as Calendar
                    tomorrow.add(Calendar.DAY_OF_MONTH, 1)
                    dateFormat.format(tomorrow.time)
                }
                "后天" -> {
                    val dayAfterTomorrow = today.clone() as Calendar
                    dayAfterTomorrow.add(Calendar.DAY_OF_MONTH, 2)
                    dateFormat.format(dayAfterTomorrow.time)
                }
                else -> key
            }
            Triple(key, taskList, sortKey)
        }
        .sortedBy { (_, _, sortKey) ->
            try {
                SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(sortKey)
            } catch (e: Exception) {
                Date(Long.MAX_VALUE) // 解析失败的放最后
            }
        }
        .forEach { (key, taskList, _) ->
            sortedGroups.add(TaskGroup(key, taskList))
        }
        
        return sortedGroups
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_REFRESH) {
            // 重新观察任务数据
            observeTasks()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 重新观察任务数据
        observeTasks()
    }
}